#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@File: DatabaseCheck.py
@Author: lijk34925 
@Date: 2024/4/3 17:07
@desc: 请补充本模块功能说明
"""
import re

from qturboframe.lib.utils.variable import Variable
from qturboframe.lib.webdriver import SeleniumError

from AmlScripts.BasicFunction.common_test_prepare import test_db_link
from BladeFerm.Lib.Common import logger
from BladeFerm.databases import DB_APP


BladeVariable = Variable()


@test_db_link
def check_indexes_condition(input_data=None, ui_expect=None):
    """
    风险评估指标基础数据检查，是否存在符合条件的数据
    :param input_data:
        - tables: 表1，表2，表3
        - * rules_no: 规则编号
        - * company_no： 公司号
        - * finance_industry_class: 金融行业分类
    :param ui_expect:
        - total: 数量
    :return: 校验不通过则报异常
    """
    # 默认检查的表  "hsamlrc.amlrc_cfg_conditionparam_list" ---不一定有数据
    tables_list = ["hsamlrc.amlrc_cfg_dimensioninfo_list", "hsamlrc.amlrc_cfg_rule_list",
                   "hsamlrc.amlrc_cfg_rulesql_list", "hsamlrc.amlrc_cfg_rulecondinfo_list",
                   "hsamlrc.amlrc_cfg_rulescore_list", "hsamlrc.amlrc_cfg_rulescoreinfo_list"]
    tables_parameters = ["hsamlrc.amlrc_cfg_dimensioninfo", "hsamlrc.amlrc_cfg_rule", "hsamlrc.amlrc_cfg_rulecondinfo",
                         "hsamlrc.amlrc_cfg_rulescore", "hsamlrc.amlrc_cfg_rulescoreinfo", "hsamlrc.amlrc_cfg_rulesql"]
    env = BladeVariable.get_variable('varg_db_type')
    logger.info(f"test env: {env}")
    env = env if env and env != 'AGENT_EMPTY' else 'mysql'
    new_tables = input_data.get("tables", "_list")
    tables = tables_list if re.search("_list", new_tables, re.I) else tables_parameters
    company_no = input_data.get("company_no", None)
    rules_no = input_data.get("rules_no", None)
    finance_industry_class = input_data.get("finance_industry_class", None)
    logger.info(f"检查风险评估指标表，条件是：rules_no： {rules_no}，company_no： {company_no}")
    expect_total = ui_expect.get("TOTAL", 1)
    for table in tables:
        if not table.startswith('hsaml'):
            table = 'hsamlrc.' + table
        columns = __get_table_columns(table, env)
        sql = f"SELECT count(1) as TOTAL FROM {table} where rules_no = '{rules_no}'"
        if company_no and company_no.upper() in columns:
            sql += f" AND company_no = '{company_no}'"
        if finance_industry_class and finance_industry_class.upper() in columns:
            sql += f" AND finance_industry_class = '{finance_industry_class}'"
        result = DB_APP.run_one_sql(sql)
        if result and int(result[0].get('TOTAL')) >= int(expect_total):
            logger.info(f"检查表 {table} 存在 {len(result)} 条符合条件的数据!")
        else:
            error_info = f"检查表 {table} 不存在符合条件的数据!"
            logger.error(error_info)
            raise SeleniumError(error_info)


@test_db_link
def check_rules_condition(input_data=None, ui_expect=None):
    """
    可疑规则 的基础数据检查，是否存在符合条件的数据
    :param input_data:
        - tables: 表1，表2，表3
        - * rules_no: 规则编号
        - * rule_version： 规则版本
        - * finance_industry_class_list： 行业
    :param ui_expect:
        - total: 数量
    :return: 校验不通过则报异常
    """
    # 默认检查的表
    env = BladeVariable.get_variable('varg_db_type')
    logger.info(f"test env: {env}")
    env = env if env and env != 'AGENT_EMPTY' else 'mysql'
    tables_list = ["hsamlls.amlls_cfg_rule_list", "hsamlls.amlls_cfg_rulesql_list",
                   "hsamlls.amlls_cfg_ruleparameter_list", "hsamlls.amlls_cfg_ruleproposal_list"]
    tables_params = ["hsamlls.amlls_cfg_rule", "hsamlls.amlls_cfg_ruleparameter",
                     "hsamlls.amlls_cfg_ruleproposal", "hsamlls.amlls_cfg_rulesql"]
    new_tables = input_data.get("tables", None)
    tables = tables_list if re.search("_list", new_tables, re.I) else tables_params
    rules_no = input_data.get("rules_no", None)
    rule_version = input_data.get("rule_version", None)
    finance_industry_class_list = input_data.get("finance_industry_class_list", None)
    logger.info(f"检查可疑规则表，条件是：rules_no： {rules_no}，rule_version： {rule_version}, "
                f"finance_industry_class_list: {finance_industry_class_list}")
    expect_total = ui_expect.get("total", 1)
    for table in tables:
        if not table.startswith('hsaml'):
            table = 'hsamlls.' + table
        columns = __get_table_columns(table, env)
        sql = f"SELECT count(1) as TOTAL FROM {table} where rules_no = '{rules_no}'"
        if rule_version and rule_version in columns:
            sql += f" AND rule_version = '{rule_version}'"
        if finance_industry_class_list and finance_industry_class_list in columns:
            sql += f" AND rule_version like '%{finance_industry_class_list}%'"
        result = DB_APP.run_one_sql(sql)
        check_result = False
        if result and int(result[0].get('TOTAL')) >= int(expect_total):
            logger.info(f"检查表 {table} 存在 {len(result)} 条符合条件的数据!")
            check_result = True
        elif result and int(result[0].get('TOTAL')) == 0:
            sql2 = f"SELECT count(1) as TOTAL FROM hsamlls.amlls_cfg_open_rule where rules_no = '{rules_no}'"
            result2 = DB_APP.run_one_sql(sql2)
            if result2 and int(result2[0].get('TOTAL')) >= int(expect_total):
                logger.info(f"检查表 {table} 存在 {len(result2)} 条符合条件的数据!")
                check_result = True
        if not check_result:
            error_info = f"检查表 {table} 不存在符合条件的数据!"
            logger.error(error_info)
            raise SeleniumError(error_info)


def __get_table_columns(table, env):
    sql = f"SELECT * from {table} where 1=1 limit 1"
    result = DB_APP.run_one_sql(sql)
    if result:
        columns = list(result[0].keys())
    else:
        columns = None
    return columns
